package com.darkteam.jhades.cs;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.darkteam.jhades.common.MessageReceivedHandler;
import com.darkteam.jhades.common.message.ResponseMessage;

public class ConnectServerHandler extends SimpleChannelUpstreamHandler {
	
	private static final Logger logger = Logger.getLogger(     ConnectServerHandler.class.getName());

	private Map<Short, MessageReceivedHandler> handlers = Collections.synchronizedMap(new HashMap<Short, MessageReceivedHandler>());
	
	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		super.channelOpen(ctx, e);
		ResponseMessage message = new ResponseMessage((short) 0x0001);		
		sendMessage(e, message);
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		super.messageReceived(ctx, e);
		ResponseMessage message = (ResponseMessage) e.getMessage();
		MessageReceivedHandler messageReceivedHandler = handlers.get(message.getFunction());
		if(messageReceivedHandler != null){
			messageReceivedHandler.messageReceived(ctx, e);
		}	
	}

	private void sendMessage(ChannelStateEvent e, ResponseMessage message) {
		Channel channel = e.getChannel();
		channel.write(message);

	}

	public MessageReceivedHandler addMessageReceivedHandler(Short key, MessageReceivedHandler value) {
		return handlers.put(key, value);
	}
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		logger.log(Level.WARNING, "Unexpected exception from downstream.", e.getCause());
		e.getChannel().close();
	}
	
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		logger.info("Client disconnected: " + e.getChannel().getRemoteAddress() );
	}
	
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		logger.info("Client connected: " + e.getChannel().getRemoteAddress() );
	}
	
	

}
